﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using VH.SharePoint.Api.Entensions;
using VH.SharePoint.Api.Helpers;

namespace VH.SharePoint.Api
{
    public abstract class ObjectCollection<T> : IEnumerable<T> where T:BlogItem
    {
        public abstract SPQuery Query { get; protected set; }

        public IEnumerator<T> GetEnumerator()
        {
            return List.GetItems(Query).Cast<SPListItem>().Select(item => item.ToBlogItem<T>()).GetEnumerator();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public T this[int id]
        {
            get { 
                var result = this.List.GetItemById(id);
                return result.ToBlogItem<T>();
            }
        }

        protected BlogWeb Blog { get; private set; }
        protected SPList List { get; private set; }

        protected ObjectCollection(BlogWeb blog, Guid targetList)
        {
            Blog = blog;
            List = GetTargetList(targetList);
        }

        public void Update()
        {

            using(new SPUnsafeUpdate(List.ParentWeb))
                List.Update();
        }

        public void Delete(int id)
        {
            using (new SPUnsafeUpdate(List.Lists.Web))
            {
                List.Items.DeleteItemById(id);
            }
        }

        private SPList GetTargetList(Guid id)
        {
            return Blog.Web.Lists[id];
        }
    }
}